package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.SetMealDto;
import com.itheima.mapper.SetMealMapper;
import com.itheima.pojo.SetMeal;
import com.itheima.pojo.SetMealDish;
import com.itheima.service.SetMealDishService;
import com.itheima.service.SetMealService;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;


@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, SetMeal>implements SetMealService {

    @Autowired
    private SetMealDishService setMealDishService;
    @Override
    public void addMealDish(SetMealDto setMealDto) {
        this.save(setMealDto);

        Long setMealId = setMealDto.getId();

        List<SetMealDish> setmealDishes = setMealDto.getSetmealDishes();
        setmealDishes = setmealDishes.stream().map(new Function<SetMealDish, SetMealDish>() {
            @Override
            public SetMealDish apply(SetMealDish setmealDish) {
                setmealDish.setSetmealId(setMealId);
                return setmealDish;
            }
        }).collect(Collectors.toList());

        setMealDishService.saveBatch(setmealDishes);

    }

    @Override
    public SetMealDto selectById(Long id) {
        SetMeal setMeal = this.getById(id);
        SetMealDto setMealDto = new SetMealDto();
        BeanUtils.copyProperties(setMeal,setMealDto);
        LambdaQueryWrapper<SetMealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetMealDish::getSetmealId,id);
        List<SetMealDish> setMealDishList = setMealDishService.list(lqw);
        setMealDto.setSetmealDishes(setMealDishList);
        return setMealDto;
    }

    @Override
    public void updateMeal(SetMealDto setMealDto) {
        this.updateById(setMealDto);

        Long setMealId = setMealDto.getId();
        LambdaQueryWrapper<SetMealDish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SetMealDish::getSetmealId,setMealId);

        setMealDishService.remove(lqw);

        List<SetMealDish> setmealDishes = setMealDto.getSetmealDishes();
        for (SetMealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setMealId);
            setMealDishService.save(setmealDish);
        }


    }
}
